﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.cruxomatic.DTOs;
using com.cruxomatic.security;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class RestServices_SecurityService : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Params["Operation"] != null && Request.Params["Operation"].ToLower() == "authenticate")
            AuthenticateRequest(Request.Params["AdditionalParameters"]);
        if (Request.Params["Operation"] != null && Request.Params["Operation"].ToLower() == "getusers")
            GetUsersForCompany(Request.Params["AdditionalParameters"]);
        

    }

    private void GetUsersForCompany(string AdditionalParameters)
    {
        var results = JsonConvert.DeserializeObject<dynamic>(AdditionalParameters);
        string username = results.Username;
        string hashedpassword = results.Password;

        ICruxSecurityManager manage = CruxSecurityManagerFactory.GetSecurityManager();
        UserInformation user = new UserInformation();
        if (manage.AuthenticateUser(username, hashedpassword))
        {
            user = manage.GetUser(username);
            List<UserInformation> users = manage.GetUsers(user.CompanyID);
            string Json = JsonConvert.SerializeObject(users, Formatting.Indented);
            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(Json);
            Response.End();
        }
       
    }

    private void AuthenticateRequest(string AdditionalParameters)
    {
        var results = JsonConvert.DeserializeObject<dynamic>(AdditionalParameters);
        string username = results.Username;
        string hashedpassword = results.Password;

        ICruxSecurityManager manage = CruxSecurityManagerFactory.GetSecurityManager();
        UserInformation user = new UserInformation();
        if (manage.AuthenticateUser( username, hashedpassword))
        {
            user = manage.GetUser(username);
        }
        string Json = JsonConvert.SerializeObject(user);

        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(Json);
        Response.End();
    }

}